package com.cumin.shiyin.core.wrapper;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author YangJian.Kan
 * @version 1.0
 * @date 2020/4/15 13:29
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request the {@link HttpServletRequest} to be wrapped.
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (null != value) {
            value = StringEscapeUtils.escapeHtml4(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = StringEscapeUtils.escapeHtml4(values[i]);

        }
        return encodedValues;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (StrUtil.equalsIgnoreCase(getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            return super.getInputStream();
        }
        @Cleanup ServletInputStream servletInputStream = super.getInputStream();
        String body = StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeJson(IoUtil.read(servletInputStream, CharsetUtil.CHARSET_UTF_8)));
        return new XssServletInputStream(body);
    }


    private static class XssServletInputStream extends ServletInputStream {
        private final InputStream inputStream;

        public XssServletInputStream(String body) {
            inputStream = IoUtil.toStream(body, CharsetUtil.CHARSET_UTF_8);
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @SneakyThrows
        @Override
        public int read() {
            return inputStream.read();
        }
    }
}
